/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sessionBeans;

import Entities.Messages;
import Entities.Messages_;
import Entities.Reply;
import Entities.Reply_;
import TwatClasses.MessageComparator;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *
 * @author xespin
 */
@Stateless
@LocalBean
public class messagingSessionBean implements messagingSessionBeanLocal {
    
    @EJB
    private loginSessionBean m_eBeanLoginSession;
    
    @PersistenceContext
    private EntityManager m_entityManager;
    
    
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    public void sendTwat(String text, String receiver ,String login){
        //Retrieval of the receiver ID
        Long recId = m_eBeanLoginSession.getReceiverId(receiver);
        Long sendId = m_eBeanLoginSession.getReceiverId(login);
        
        Calendar cal = new GregorianCalendar();
        
        String fullMessage = "-=" + login + "=-\r\n";
        
        if(!receiver.equals("")){
            fullMessage += " @" + receiver + " \r\n" + text;
        }else{
            fullMessage += text;
        }

        Messages message = new Messages();
        message.setDate(cal.getTime());
        message.setText(fullMessage);
        if(!receiver.equals("") && !recId.equals(-1)){
            message.setReceiver(receiver);
        }
        message.setUseridfk(m_eBeanLoginSession.getReceiverId(login));
        
        m_entityManager.persist(message);
        m_entityManager.flush();
        
       //Post a shout to someone
       if(!receiver.equals("") && !recId.equals(-1)){
            Reply reply = new Reply();
            reply.setMessageidfk(message.getId());
            reply.setSenderidfk(sendId);
            reply.setReceiveridfk(recId);
            
            m_entityManager.persist(reply);
            m_entityManager.flush();
        }
    }
    
    /**
     * Gets the messages for the given user ID
     * @param login
     * @return 
     */
    public List<Messages> getTwats(String login){
        Long userID = m_eBeanLoginSession.getReceiverId(login);
        
        
        List<Messages> shoutList = null;
        //recuperation des mreponses par ID
        CriteriaBuilder cBuilder = m_entityManager.getCriteriaBuilder();
        
        CriteriaQuery<Reply> queryReply = cBuilder.createQuery(Reply.class);
        Root<Reply> rootReply = queryReply.from(Reply.class);
        queryReply.where(cBuilder.equal(rootReply.get(Reply_.receiveridfk),userID));
        queryReply.select(rootReply);
        
        try{
            List<Reply> messReply = m_entityManager.createQuery(queryReply).getResultList();
            
            Collection<Long> replyIds = new ArrayList<Long>();
            for(Reply repId: messReply){
                replyIds.add(repId.getMessageidfk());
            }
            
            if(!replyIds.isEmpty()){
                CriteriaQuery<Messages> queryMess = cBuilder.createQuery(Messages.class);
                Root<Messages> rootMessages = queryReply.from(Messages.class);
                queryMess.where(rootMessages.get(Messages_.id).in(replyIds));
                queryMess.orderBy(cBuilder.desc(rootMessages.get(Messages_.date)));
                queryMess.select(rootMessages);

                try{
                    shoutList = m_entityManager.createQuery(queryMess).getResultList();
                }catch(NoResultException  ex){
                    //nothing
                }
            }
        }catch(NoResultException  ex){
            //nothing
        }
        
        //récupération des messages
        CriteriaQuery<Messages> query = cBuilder.createQuery(Messages.class);
        Root<Messages> root = query.from(Messages.class);
        query.where(cBuilder.and(cBuilder.equal(root.get(Messages_.useridfk),userID)));
        query.orderBy(cBuilder.desc(root.get(Messages_.date)));
        query.select(root);
        
        try{
            List<Messages> messList = m_entityManager.createQuery(query).getResultList();
            if(shoutList != null){
                 messList.addAll(shoutList);
            }
            return messList;
        }catch(NoResultException  ex){
            return null;
        }
    }
    
    /**
     * Gets the replies for  this message ID
     * @param receiverId
     * @param messageId
     * @return 
     */
    public List<Messages> getReplies(Long receiverId, Long messageId){
        //MessageReply messreply = new MessageReply();
        
        return getReplie(receiverId, messageId);
    }
    
     public List<Messages> getReplie(Long receiverId, Long messageId){
        
        List<Messages> messList = null;
        Comparator<Messages> messageComparator = new MessageComparator();
        //recuperation des mreponses par ID
        CriteriaBuilder cBuilder = m_entityManager.getCriteriaBuilder();
        
        CriteriaQuery<Reply> queryReply = cBuilder.createQuery(Reply.class);
        Root<Reply> rootReply = queryReply.from(Reply.class);
        queryReply.where(cBuilder.and(cBuilder.equal(rootReply.get(Reply_.receiveridfk),receiverId),
                cBuilder.equal(rootReply.get(Reply_.messageidfk), messageId)));
        queryReply.select(rootReply);
        
        try{
            List<Reply> messReply = m_entityManager.createQuery(queryReply).getResultList();
            
            HashSet<Long> replyIds = new HashSet<Long>();
            for(Reply repId: messReply){
                replyIds.add(repId.getId());
            }
            
            if(!replyIds.isEmpty()){
                CriteriaQuery<Messages> queryMess = cBuilder.createQuery(Messages.class);
                Root<Messages> rootMessages = queryReply.from(Messages.class);
                queryMess.where(rootMessages.get(Messages_.id).in(replyIds));
                queryMess.orderBy(cBuilder.desc(rootMessages.get(Messages_.date)));
                queryMess.select(rootMessages);
            
                try{
                    messList = m_entityManager.createQuery(queryMess).getResultList();
                    Collections.sort(messList,messageComparator);
                    return messList;
                }catch(NoResultException  ex){
                    return null;
                }
            }
            return null;
        }catch(NoResultException  ex){
            return null;
        }
    }
}
